package com.example.demo.jucConcurrent.CopyOnWriteArrayList详解;

import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 下面是通过实例来了解CopyOnWriteArrayList的使用,有一个putThread线程会每隔50ms就向CopyOn
 * WriteArayList的Object数组的快照的内容,在迭代的过程中,往CopyOnWriteArrayList中添加元素不会抛出异常
 */
public class CopyOnWriteArrayListDemo {
    public static void main(String[] args) {
        CopyOnWriteArrayList<Integer> cowal = new CopyOnWriteArrayList();
        for (int i = 0; i < args.length; i++) {
            cowal.add(i);
        }
        PutThread p1 = new PutThread(cowal);
        p1.start();
        Iterator<Integer> iterator = cowal.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next() + "");
        }
        System.out.println();

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        iterator = cowal.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next() + "");
        }
    }
}

class PutThread extends Thread {

    private CopyOnWriteArrayList<Integer> cowal;

    public PutThread(CopyOnWriteArrayList<Integer> cowal) {
        this.cowal = cowal;
    }

    @Override
    public void run() {
        for (int i = 100; i < 110; i++) {
            cowal.add(i);
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}